<template>
  <n-modal v-model:show="showModal" preset="dialog" :show-icon="false">
    <n-card class="w-30vw min-h-500px">
      <n-tree
          block-line
          cascade
          multiple
          checkable
          :data="treeData"
          :selected-keys="selectedKeys"
          selectable
          @update:checked-keys="updateCheckedKeys"
      />
      <template #action>
        <div class="w-full h-10 flex justify-end items-center">
          <n-button @click="doClose">取消</n-button>
          <n-button @click="handleOK" type="primary">保存</n-button>
        </div>
      </template>
    </n-card>
  </n-modal>
</template>

<script setup name="addmenumodel">
import {useRoute, useRouter} from "vue-router";
import http from "@/request/request"
import {arrayToTree} from "../../../../util/arraytotree";

const router = useRouter()
const route = useRoute()
const showModal = ref(false)    // 模态框的显示
const parent = ref({})    // 父级数据
const treeData = ref([])    // tree数据
const flatdata = ref([])  // 数组数据，备份用的
const selectedKeys = ref([])    // 被选中的数据
const emit = defineEmits(["shuaxin"])
// 弹窗初始化
const init = (item = null) => {
  if (item) {
    parent.value = item
  }
  showModal.value = true
}
const doClose = () => {
  showModal.value = false
  emit("shauxin")
  reset()
}
const reset = () => {

}
// 点击确定
const handleOK = () => {
  selectedKeys.value.forEach(item=>{
    const jieguo = flatdata.value.find(el=>el.id===item)
    jieguo.show = true
    if(jieguo.parent){
      setshow(jieguo.parent)
    }
  })
  console.log(flatdata.value,"情况如何")
}

// 获取所有数据
const getalldata = () => {
  http.menuall().then(res => {
    if (res.data.code === 0) {
      flatdata.value = [...res.data.items]    // 保留一份扁平数据
      treeData.value = arrayToTree(res.data.items.map(item => {
        return {label: item.name, key: item.id, parent: item.parent,}
      })) // 将扁平数据改造成树状数据
    }
  })
}
// 勾选的回调
const updateCheckedKeys = (items) => {
  console.log(items, "都是什么")
  selectedKeys.value = items
}
// 遍历选中的数据，在扁平数据中，将所以选中数据的父级都设置为false
const setshow=(itemid)=>{
  const jieguo = flatdata.value.find(el=>el.id===itemid)
  jieguo.show = true
  if(jieguo.parent){
    setshow(jieguo.parent)
  }
}

// 抛出方法和属性
defineExpose({init, doClose, reset})
// 初始化区域
getalldata()
</script>

<style scoped>

</style>
